package org.weike.mobile.api.interceptor;

import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.wk.core.common.view.ResponseVo;
import org.wk.core.db.domain.IUser;
import org.wk.core.db.tool.WebUtils;
import org.wk.user.service.LoginTokenService;
import org.wk.user.view.UserDetailVo;

import com.google.common.base.Strings;

/**
 * 
 * @ClassName	: LoginInterceptor
 * @Package		：org.weike.mobile.api.interceptor
 * @Author df.w 
 * @Create Time	：2018年5月3日 下午3:12:55
 * @Description	: 登录拦截
 */
public class LoginInterceptor implements HandlerInterceptor {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private LoginTokenService loginTokenService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String requestURI = request.getRequestURI();
		logger.info("访问url-----{}",requestURI);
//		BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
//		String body = IOUtils.read(reader);
//		logger.info(body);
		String token = request.getParameter("token");
		logger.info("token------{}",token);
		if (!Strings.isNullOrEmpty(token)) {
			UserDetailVo userDetailVo = loginTokenService.getLoginInfoByToken(token);
			if (userDetailVo != null) {
				IUser user = (IUser) userDetailVo;
				WebUtils.setUser(user);
				return true;
			}
		}
		
		if(isIgnore(requestURI)){
			return true;
		}
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = null ;
		try{  
		    ResponseVo responseVo = new ResponseVo();
		    responseVo.setCode("no_login");
		    responseVo.setMessage("未登录");
		    out = response.getWriter();
		    logger.info("......{}",responseVo.toString());
		    out.append(responseVo.toString());
			response.sendRedirect("/");
		    return false;  
		}catch (Exception e){  
		    e.printStackTrace();  
		    response.sendError(500);
		    return false;  
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		WebUtils.clear();// 清空内容
	}
	
	
	/**
	* @Title		: isIgnore
	* @Param		: @param path
	* @Param		: @return
	* @Return Type 	：boolean
	* @Description	: 忽略的地址
	*/
	public boolean isIgnore(String path){

		if (path.startsWith("/app-api")) {
			path = path.replaceAll("/app-api","");
		}

		Set<String> ignoreSet = new HashSet<String>();
		//登录
		ignoreSet.add("/");
		//修改密码
		ignoreSet.add("/forgetpasds");
		//注册
		ignoreSet.add("/register");
		//修改用户信息
		ignoreSet.add("/updateProfile");
		//设置
		ignoreSet.add("/install");
		//申请升级
		ignoreSet.add("/apply");
		//审核升级
		ignoreSet.add("/Auditing");
		//我的团队
		ignoreSet.add("/team");
		//商家信息
		ignoreSet.add("/business");
		//历史信息
		ignoreSet.add("/history");

		//进入首页
		ignoreSet.add("/index");
		//忘记密码
		ignoreSet.add("/forgetpasd");
		//注册
		ignoreSet.add("/users/register");
		//获取短信验证码
		ignoreSet.add("/mobile_phone/send_code");
		//通过手机验证码重置登录密码
		ignoreSet.add("/passwords/login_password/reset_password_via_mobile");
		//用户登录
		ignoreSet.add("/users/login");
		ignoreSet.add("/users/promote/register");
		ignoreSet.add("/users/promote/referral_code");
		return ignoreSet.contains(path)||path.startsWith("/pages")||path.startsWith("/notice")||path.startsWith("/agreement")
				||path.endsWith(".css")||path.endsWith(".js")||path.endsWith(".png")|| path.startsWith("/news");
	}
	/**
	* @Title		: isLoginIgnore
	* @Param		: @param path
	* @Param		: @return
	* @Return Type 	：boolean
	* @Description	: 已登录忽略的地址
	*/ 
	public boolean isLoginIgnore(String path){
		Set<String> ignoreSet = new HashSet<>();
		ignoreSet.add("/logout");
		ignoreSet.add("/user.html");
		return ignoreSet.contains(path);
	}
}
